<template>
	<el-dialog :title="title" v-model="open" append-to-body :close-on-click-modal="false" width="500px">
		<el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
			<el-row class="mb20" :gutter="10">
				<el-col>
					<el-form-item label="商品名称" prop="goods_id">
						<el-select v-model="form.goods_id" filterable remote clearable placeholder="请输入选择商品名称"
							:remote-method="goodsIdRemoteMethod" :loading="goodsIdLoading" @focus="onGoodsIdFocus"
							@clear="onGoodsIdClear" @change="onGoodsIdChange" class="w100">
							<el-option v-for="item in goodsIdOptions" :key="item.id" :label="item.title" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row class="mb20" :gutter="10">
				<el-col>
					<el-form-item label="直播商品名称" prop="name">
						<el-input v-model="form.name" placeholder="请输入直播商品名称" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row class="mb20" :gutter="10">
				<el-col>
					<el-form-item label="直播商品封面" prop="coverImgUrl_image">
						<template #label>
							直播商品封面<br />
							<span style="font-size: 12px; color: red">尺寸建议300*300</span><br />
							<span style="font-size: 12px; color: red">大小不超过350kb</span>
						</template>
						<image-upload-COS v-model="form.coverImgUrl_image" v-model:media_id="form.coverImgUrl" path="live" isLive
							ref="imageUploadCoverImgUrlRef" />
					</el-form-item>
				</el-col>
			</el-row>
			<!-- <el-row class="mb20" :gutter="10">
				<el-col>
					<el-form-item label="商品价格" prop="price">
						<el-input-number v-model="form.price" :min="0" :precision="2" :controls="false" placeholder="请输入商品价格"
							class="w100" />
					</el-form-item>
				</el-col>
			</el-row> -->
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" :loading="submitLoading" @click="onSubmitForm">确定</el-button>
				<el-button @click="onCancel">取消</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts">
import { nextTick, reactive, ref, toRefs } from 'vue';
import { ElMessage } from 'element-plus';

import { livesApi } from '/@/api/admin';
import { stringNum } from '/@/utils/toolsValidate';

const LivesApi = livesApi()
export default {
	name: 'libraryGoodAddDialog',
	setup() {
		const validateName = (rule: any, value: any, callback: Function) => {
			let _value: any = stringNum(value) / 2;
			if (parseInt(_value) > 14) {
				callback(new Error('商品名称，最短3个汉字，最长14个汉字，1个汉字相当于2个字符'));
			} else if (2 >= parseInt(_value)) {
				callback(new Error('商品名称，最短3个汉字，最长14个汉字，1个汉字相当于2个字符'));
			} else {
				callback();
			}
		};
		const state = reactive({
			title: '添加商品审核',
			open: false,
			goodsIdOptions: [] as any,
			goodsIdLoading: false,
			form: {} as any,
			rules: {
				goods_id: [{ required: true, message: '商品名称不能为空', trigger: ['blur', 'change'] }],
				name: [
					{ required: true, message: '直播商品名称不能为空', trigger: 'blur' },
					{ required: true, validator: validateName, trigger: 'blur' },
				],
				coverImgUrl_image: [{ required: true, message: '直播商品封面不能为空', trigger: ['blur', 'change'] }]
			}, // 表单校验
			submitLoading: false,
		});

		const formRef = ref(null);
		const imageUploadCoverImgUrlRef = ref(null);
		let callback: Function = () => { };

		/********** 点击事件(on开头) **********/
		// 选择商品
		const onGoodsIdFocus = () => {
			if (!state.form.goods_id) {
				state.goodsIdLoading = true;
				_selectLivesGoodsList();
			}
		};
		// 清空商品
		const onGoodsIdClear = () => {
			_selectLivesGoodsList();
		};
		// 选中商品
		const onGoodsIdChange = (val: number) => {
			let goodsIdOption:any = state.goodsIdOptions.find((item: any) => item.id == val);
			state.form.name = goodsIdOption.title;
			state.form.price = Number(goodsIdOption.sale_price);
		};
		/** 提交按钮 */
		const onSubmitForm = () => {
			(formRef.value as any)?.validate((valid: boolean) => {
				if (valid) {
					state.submitLoading = true;
					console.log('state.form', state.form);
					_livesGoodsListApply({
						...state.form,
						url: 'pagesCommon/goodDetails/index?goods_id=' + state.form.goods_id,
						coverImgUrl_image: state.form.coverImgUrl_image.replace(import.meta.env.VITE_FILE_API, ''),
					});
				}
			});
		};
		// 取消按钮
		const onCancel = () => {
			state.submitLoading = false;
			state.open = false;
			reset();
		};

		/********** 方法事件 **********/
		//打开
		const openDialog = (config: any, fn: Function) => {
			console.log(config);
			reset();
			callback = fn;
			state.open = true;
			nextTick(() => {
				(imageUploadCoverImgUrlRef.value as any)?.dataLoading();
			});
		};
		// 表单重置
		const reset = () => {
			state.form = {
				goods_id: '',
				name: '',
				coverImgUrl_image: '',
				coverImgUrl: '',
				price_type: 1,
				price: 0,
			};
			(formRef.value as any)?.resetFields();
			nextTick(() => {
				(imageUploadCoverImgUrlRef.value as any)?.reset();
			});
		};
		// 商品搜索
		const goodsIdRemoteMethod = (query: string) => {
			if (query) {
				state.goodsIdLoading = true;
				_selectLivesGoodsList({ name: query });
			} else {
				return true;
			}
		};

		/********** 网络事件 **********/
		// 获取可选择提审的商品列表
		const _selectLivesGoodsList = (params: object = {}) => {
			LivesApi.selectLivesGoodsList(params)
				.then((res: any) => {
					state.goodsIdOptions = res.data.list;
					state.goodsIdLoading = false;
				})
				.catch(() => {
					state.goodsIdLoading = false;
				});
		};
		// 提交商品审核
		const _livesGoodsListApply = (params: object) => {
			LivesApi.livesGoodsListApply(params)
				.then(() => {
					ElMessage.success('提交成功，等待微信审核');
					onCancel();
					callback();
				})
				.catch(() => {
					state.submitLoading = false;
				});
		};

		return {
			formRef,
			imageUploadCoverImgUrlRef,
			onGoodsIdFocus,
			onGoodsIdClear,
			onGoodsIdChange,
			onSubmitForm,
			openDialog,
			onCancel,
			goodsIdRemoteMethod,
			...toRefs(state),
		};
	},
};
</script>

<style lang="scss" scoped>
</style>
